// @ts-nocheck
/* config */
import platform from '@src/platform';
import { isFunction } from '@src/util/type'
/* form */
import { FormFieldMap } from '@src/mform/components'
import Vue from 'vue'

import { t } from '@src/locales'

/** 通用验证 */
function common(field) {
  let message = [];
  
  return message;
}

/**
 * 验证表单字段格式
 * @param {array} fields - 待验证字段
 * @returns error message array or error message
 */
export function validate(fields) {
  return fields
    .map((field, index) => {
      let formType = field.formType
      let message = common(field);
      
      const fieldConfig = FormFieldMap.get(formType)
      if (fieldConfig && isFunction(fieldConfig.validateFunction)) {
        const validateMessages = fieldConfig.validateFunction(field) || []
        message = message.concat(validateMessages)
      }
      
      return message.length > 0 ? { message, title: field.displayName, field, index } : null;
    })
    .filter(i => i != null);
}

/**
 * 默认提示，可自行根据内容提示
 * @param {string | array} message - 提示内容
 * @param {function} createElement - vue createElement function
 * @returns true - 验证成功，无提示信息。 false - 验证失败，有提示信息
 */
export function notification(message) {
  if (typeof message == 'string' && message.length > 0) {
    platform.notification({
      type: 'error',
      title: t('common.validate.checkTitle'),
      message
    });
    
    return false;
  }
  
  if (Array.isArray(message) && message.length > 0) {
    let arrHtml = message.length && message.map(item=>{
      let arrhtml_ = item.message.length && item.message.map(item_=>`<p>- ${item_}</p>\n`)
      return `<h3>${item.title}</h3>\n${arrhtml_}`
    })
    let html_ = `<div class="form-design-notification">${arrHtml}</div>`
    platform.notification({
      type: 'error',
      title: t('common.validate.checkField'),
      duration: 0,
      dangerouslyUseHTMLString: true,
      // message: (function (h) {
      //   let content = message.map(i => {
      //     // eslint-disable-next-line
      //     let nodes = i.message.map(m => <p>- {m}</p>);
      //     nodes.unshift(<h3>{i.title}</h3>);
      //     return nodes;
      //   });
        
      //   return (<div class="form-design-notification">{content}</div>);
      // })
      message:html_
    });
    
    return false;
  }
  
  return true;
}

export function setFieldError(errorDataList) {
  errorDataList.forEach(errorData => {
    let field = errorData?.field || {}
    Vue.set(field, 'isError', true)
  })
}

/**
 * 判断对象为空
 * @param {*} value 对象
 * @returns {Boolean} {} [] undefined|null 等返回 false
 */
const _isEmpty = value => (
  value === undefined ||
  value === null ||
  (typeof value === 'object' && Object.keys(value).length === 0) ||
  (typeof value === 'string' && value.trim().length === 0)
);


